from rest_framework import serializers
from ..models import *
from datetime import datetime
import re


# 单位表
class FaKuyouUnitSerializer(serializers.ModelSerializer):
    class Meta:
        model = FaKuyouUnit
        fields = '__all__'

    def validate(self, data):
        """多单位类型下必须有一个主单位"""
        if data.get('type') == '2' and data.get('is_main') == '0':
            # 检查是否已存在主单位
            if not FaKuyouUnit.objects.filter(
                    type='2',
                    is_main='1'
            ).exclude(pk=self.instance.pk if self.instance else None).exists():
                raise serializers.ValidationError({
                    'is_main': '多单位类型下必须有一个主单位'
                })
        return data


# 多单位表
class UnitConversionSerializer(serializers.ModelSerializer):
    class Meta:
        model = FaKuyouUnitConversion
        fields = '__all__'
        extra_kwargs = {
            'admin_id': {'write_only': True},
            'createtime': {'write_only': True},
            'updatetime': {'write_only': True},
        }

    def validate(self, data):
        """自定义验证"""
        # 进率验证
        if 'advance_rate' in data and float(data['advance_rate']) <= 0:
            raise serializers.ValidationError({
                'advance_rate': '换算进率必须大于0'
            })

        # 主副单位验证
        if 'main_unit' in data and 'vice_unit' in data and data['main_unit'] == data['vice_unit']:
            raise serializers.ValidationError({
                'vice_unit': '副单位不能与主单位相同'
            })

        return data


# 委外加工表
class FaKuyouFactorySerializer(serializers.ModelSerializer):
    class Meta:
        model = FaKuyouFactory
        fields = '__all__'

    def validate(self, data):
        """财务数据验证"""
        if 'receive_account' in data and 'opening_prepayment' in data:
            if data['receive_account'] is not None and data['opening_prepayment'] is not None:
                if data['receive_account'] < data['opening_prepayment']:
                    raise serializers.ValidationError({
                        'opening_prepayment': '期初预收款不能大于期初应收款'
                    })
        return data

    def to_representation(self, instance):
        """序列化处理"""
        ret = super().to_representation(instance)
        return ret


# 供应商表
class FaKuyouSuppliersSerializer(serializers.ModelSerializer):
    class Meta:
        model = FaKuyouSuppliers
        fields = '__all__'

    def validate_first_connect_mobile(self, value):
        """验证手机号码格式"""
        if not re.match(r'^1[3-9]\d{9}$', value):
            raise serializers.ValidationError("手机号码格式不正确")
        return value

    def validate_identification(self, value):
        """验证纳税人识别号"""
        if value and len(value) not in [15, 18, 20]:
            raise serializers.ValidationError("纳税人识别号应为15/18/20位")
        return value

    def validate_vat_rate(self, value):
        """验证增值税税率"""
        if value is not None and (value < 0 or value > 100):
            raise serializers.ValidationError("增值税税率应在0-100之间")
        return value

    def validate(self, data):
        """财务数据验证"""
        if 'receive_account' in data and 'opening_prepayment' in data:
            if data['receive_account'] is not None and data['opening_prepayment'] is not None:
                if data['receive_account'] < data['opening_prepayment']:
                    raise serializers.ValidationError({
                        'opening_prepayment': '期初预付款不能大于期初应付款'
                    })
        return data

    def to_representation(self, instance):
        """序列化处理"""
        ret = super().to_representation(instance)
        return ret


# 客户表
class FaKuyouCustomerSerializer(serializers.ModelSerializer):
    class Meta:
        model = FaKuyouCustomer
        fields = '__all__'
        extra_kwargs = {
            'id': {'read_only': True},
        }


# 客户等级表
class FaKuyouCustomerLevelSerializer(serializers.ModelSerializer):
    is_active = serializers.SerializerMethodField()

    class Meta:
        model = FaKuyouCustomerLevel
        fields = '__all__'
        extra_kwargs = {
            'admin_id': {'write_only': True}
        }


# 客户分类
class FaKuyouCustomerTypeSerializer(serializers.ModelSerializer):
    full_path = serializers.SerializerMethodField()

    class Meta:
        model = FaKuyouCustomerType
        fields = ['id', 'type_name', 'full_path', 'type_image', 'status']

    def get_full_path(self, obj):
        """获取完整分类路径"""
        if not obj.path:
            return obj.type_name

        try:
            parent_ids = [int(id) for id in obj.path.split(',') if id != '0']
            parents = FaKuyouCustomerType.objects.filter(id__in=parent_ids).order_by('id')
            return " > ".join([p.type_name for p in parents] + [obj.type_name])
        except:
            return obj.type_name


# 单号设置
class FaKuyouPrefixSerializer(serializers.ModelSerializer):
    class Meta:
        model = FaKuyouPrefix
        fields = '__all__'
        extra_kwargs = {
            'id': {'read_only': True},
            'prefix': {
                'required': True,
                'error_messages': {
                    'blank': '前缀不能为空',
                    'null': '前缀不能为null'
                }
            },
            'type': {
                'required': True,
                'error_messages': {
                    'blank': '单据类型不能为空',
                    'null': '单据类型不能为null'
                }
            },
        }


# 支出类别
class FaKuyouExpendTypeSerializer(serializers.ModelSerializer):
    status_display = serializers.CharField(source='get_status_display', read_only=True)

    class Meta:
        model = FaKuyouExpendType
        fields = '__all__'
        extra_kwargs = {
            'createtime': {'read_only': True},
            'updatetime': {'read_only': True},
        }

    def validate_pid(self, value):
        """
        验证上级分类ID是否存在
        """
        if value != 0 and not FaKuyouExpendType.objects.filter(id=value).exists():
            raise serializers.ValidationError("指定的上级分类不存在")
        return value

    def validate(self, data):
        """
        自定义验证逻辑
        """
        # 可以添加更多的验证逻辑
        return data


# 账户表
class FaKuyouAccountsSerializer(serializers.ModelSerializer):
    account_type_id_display = serializers.CharField(source='get_account_type_id_display', read_only=True)
    is_default_display = serializers.CharField(source='get_is_default_display', read_only=True)
    status_display = serializers.CharField(source='get_status_display', read_only=True)

    class Meta:
        model = FaKuyouAccounts
        fields = '__all__'
        extra_kwargs = {
            'createtime': {'read_only': True},
            'updatetime': {'read_only': True},
            'deletetime': {'read_only': True},
        }

    def validate_account_coding(self, value):
        """
        验证账户编号唯一性
        """
        if self.instance and self.instance.account_coding == value:
            return value

        if FaKuyouAccounts.objects.filter(account_coding=value).exists():
            raise serializers.ValidationError("账户编号已存在")
        return value

    def validate(self, data):
        """
        自定义验证逻辑
        """
        # 如果设置为默认账户，需要确保同类型账户中没有其他默认账户
        if data.get('is_default') == '1':
            same_type_accounts = FaKuyouAccounts.objects.filter(
                account_type_id=data.get('account_type_id', self.instance.account_type_id if self.instance else '1'),
                is_default='1'
            )
            if self.instance:
                same_type_accounts = same_type_accounts.exclude(id=self.instance.id)
            if same_type_accounts.exists():
                raise serializers.ValidationError("同类型账户中已存在默认账户")

        return data


# 应收账款明细表
class FaKuyouAccountsReceivableSerializer(serializers.ModelSerializer):
    business_type_display = serializers.CharField(
        source='get_business_type_display',
        read_only=True
    )
    purchase_time_formatted = serializers.DateTimeField(
        source='purchase_time',
        format='%Y-%m-%d %H:%M:%S',
        read_only=True
    )

    class Meta:
        model = FaKuyouAccountsReceivable
        fields = '__all__'
        extra_kwargs = {
            'id': {'read_only': True},
        }


# 应付账款明细表
class FaKuyouAccountsCopeWithSerializer(serializers.ModelSerializer):
    business_type_display = serializers.CharField(
        source='get_business_type_display',
        read_only=True
    )
    purchase_time_formatted = serializers.DateTimeField(
        source='purchase_time',
        format='%Y-%m-%d %H:%M:%S',
        read_only=True,
        required=False
    )

    class Meta:
        model = FaKuyouAccountsCopeWith
        fields = '__all__'
        extra_kwargs = {
            'id': {'read_only': True},
        }
